/*jslint vars: true, forin: true, plusplus: true */
'use strict';

var angular = require('angular');
var probe = require('../global');
probe.service("Capture", function (uniqueSelector) {
	var contextDoc = window.document;
	var zIndex = 555;

	var editor = {
		cssPath: "",
		curJQ: null
	};

	editor.catchHTML = function (callback) {
		// return a only CSSpath
		this.cssPath = uniqueSelector.gen(this.curJQ[0]);
		// no cb
		if (typeof callback !== "function") {
			return this.cssPath;
		}
		// did not catch it properly
		if (!this.cssPath) {
			return this.cancelCatch(callback);
		}
		
		return callback(this.cssPath);
	};
	
	editor.cancelCatch = function (callback) {
		callback('');
	};

	editor.watchHTML = function (contextFrame, callback) {
		var markElement, catchElement, drawArea, eraseArea,
			left = 1,
			top = 1,
			that = this;
		var frameOffset = contextFrame.getBoundingClientRect();
		that.curJQ = null;

		var $axes = angular.element('<div id="axes"></div>');
		$axes[0].style.zIndex = zIndex;
		var $axesX = angular.element('<hr id="axes-x" />');
		var $axesY = angular.element('<hr id="axes-y" />');
		var $area = angular.element('<div class="area"></div>');
		$axes.append($axesX).append($axesY);

		markElement = function () {
			var current_element = angular.element(
				contextDoc.elementFromPoint(left - frameOffset.left, top - frameOffset.top));
			$axes[0].style.display = 'none';
			$axesX[0].style.left = left + "px";
			$axesY[0].style.top = top + "px";
			if (that.curJQ !== current_element && current_element[0]) {
				that.curJQ = current_element;
				eraseArea();
				drawArea();
			}
			$axes[0].style.display = '';
		};

		drawArea = function () {
			var ele = that.curJQ;
			var offset = ele[0].getBoundingClientRect();//offset within iframe
			// -2 for border
			$area[0].style.top = (offset.top + frameOffset.top - 2) + 'px';
			$area[0].style.left = (offset.left + frameOffset.left - 2) + 'px';
			$area[0].style.width = offset.width + 'px';
			$area[0].style.height = offset.height + 'px';

			$area[0].style.display = '';

			$axes.append($area);
		};

		eraseArea = function () {
			$area[0].style.display = 'none';
		};

		angular.element(window.document.body).append($axes);

		$axes.on('mousemove', function (event) {
			left = event.pageX;
			top = event.pageY;
			markElement();
		});

		$axes.on('click', function catchOnClick() {
			$axes.remove();
			that.catchHTML(callback);
		});

		$axes.on('contextmenu', function cancelOnRclick(e) {
			e.preventDefault();
			
			$axes.remove();
			that.cancelCatch(callback);
		});
	};
	
	editor.setContext = function (newWindow) {
		contextDoc = newWindow.document;
		
		return this;
	};
	
	editor.setZIndex = function (newIndex) {
		zIndex = newIndex;
		
		return this;
	};

	return editor;
});
